import { useEffect, useMemo, useState } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import { IReducerState, IRootReducerState } from '@/store/root-reducer';
import {
  Avatar,
  Button,
  Popconfirm,
  Space,
  Switch,
  Table,
  Typography,
} from '@douyinfe/semi-ui';
import {
  IconAlertTriangle,
  IconDeleteStroked,
  IconEditStroked,
  IconFemale,
  IconKeyStroked,
  IconMale,
} from '@douyinfe/semi-icons';
import { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { PaginationProps } from '@douyinfe/semi-ui/lib/es/pagination';
import { usePageContext } from '../context';
import TablePagination, {
  onPageParamsChange,
} from '@/widgets/table-pagination';
import { pageSizeOpts } from '../helper';
import BaseColumns from './columns';
import { forbiddenUser } from '@/redux/user/user-api';
import { useDispatch } from 'react-redux';
import { fetchItems } from '@/redux/user/user-actions';

const UserTable = () => {
  const { Text } = Typography;

  const PageContext = usePageContext();
  const dispatch = useDispatch();
  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
      setQueryParams: PageContext.setQueryParams,
      addRecord: PageContext.addRecord,
      editRecord: PageContext.editRecord,
      delRecord: PageContext.delRecord,
      detailRecord: PageContext.detailRecord,
      resetPwdRecord: PageContext.resetPwdRecord,
    };
  }, [PageContext]);

  const { user } = useSelector<IRootReducerState, any>(
    (state) => ({ user: state.user }),
    shallowEqual
  );
  const { entities, totalCount } = user;

  const columns: ColumnProps[] = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 60,
      align: 'right',
      render: (_, __, index) => (
        <>
          {(PageAction.queryParams.pageNum - 1) *
            PageAction.queryParams.pageSize +
            index +
            1}
        </>
      ),
    },
    // {
    //   title: '姓名',
    //   dataIndex: 'nickname',
    //   width: 180,
    //   // sorterKey: 'name',
    //   // sorter: true,
    //   render: (text, record, index) => {
    //     return (
    //       <div className='flex items-center'>
    //         <Avatar size='small' src={record.avatar}>
    //           {typeof text === 'string' && text.slice(0, 1)}
    //         </Avatar>
    //         <Text
    //           className='mx-2'
    //           link
    //           onClick={() => {
    //             PageAction.detailRecord(record[user.key]);
    //           }}>
    //           {text}
    //         </Text>
    //         {record.sex == 0 ? (
    //           <></>
    //         ) : record.sex == 1 ? (
    //           <IconMale className='text-sky-400' />
    //         ) : (
    //           <IconFemale className='text-pink-400' />
    //         )}
    //       </div>
    //     );
    //   },
    // },
    ...BaseColumns,
    {
      title: '状态',
      dataIndex: 'forbidden',
      render: (text, record, index) => {
        return (
          <div className='flex flex-row items-center'>
            <span
              className={`mx-1 font-bold ${
                text ? 'text-rose-500' : 'text-green-500'
              }`}
            >
              {text ? '禁用' : '正常'}
            </span>
            <Switch
              defaultChecked={!text}
              onChange={(v, e) => {
                forbiddenUser({
                  forbidden: !text,
                  userId: record?.id,
                }).then((res: any) => {
                  if (res?.data?.data) {
                    // @ts-ignore
                    dispatch(fetchItems(PageAction.queryParams)).then(
                      (res: any) => {
                        console.log(res);
                      }
                    );
                  }
                });
              }}
            ></Switch>
          </div>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record, index) => {
        return (
          <Space>
            <Button
              icon={<IconEditStroked />}
              onClick={() => {
                PageAction.editRecord(record[user.key]);
              }}
            ></Button>
            {/* <Button
              icon={<IconKeyStroked />}
              onClick={() => {
                PageAction.resetPwdRecord(record[user.key]);
              }}
            ></Button> */}
            {/* <Popconfirm
              title='确认删除改用户'
              content='请注意次操作不可逆'
              icon={
                <IconAlertTriangle
                  className='!text-red-500'
                  size='extra-large'
                />
              }
              okType='danger'
              onConfirm={() => PageAction.delRecord(record[user.key])}
            >
              <span className='inline-block invisible group-hover/item:visible'>
                <Button icon={<IconDeleteStroked />} type='danger' />
              </span>
            </Popconfirm> */}
          </Space>
        );
      },
      // // 此处从render的第四个形参中解构出 展开按钮、选择按钮、文本等内容
      // render: (text, record, index, { expandIcon, selection, indentText }) => {
      //   return <>111</>;
      // })
    },
  ];

  const onRowEvent: any = useMemo(
    () => (record: any, index: number) => {
      return {
        className: 'group/item',
      };
    },
    []
  );

  const paginationOptions = useMemo(
    () => ({
      total: totalCount,
      queryParams: PageAction.queryParams,
      pageSizeOpts,
    }),
    [PageAction, user]
  );

  return (
    <TablePagination paginationOpts={paginationOptions}>
      {(paginationOpts: PaginationProps) => (
        <Table
          size='small'
          columns={columns}
          dataSource={entities}
          onChange={(params: any) =>
            onPageParamsChange(params, PageAction.setQueryParams)
          }
          pagination={paginationOpts}
          onRow={onRowEvent}
        />
      )}
    </TablePagination>
  );
};

export default UserTable;
